<?php

namespace app\admin\controller;

use app\admin\common\library\FlowEngine;
use app\admin\model\AuthGroup;
use app\admin\model\Department;
use app\admin\model\JournWeek;
use app\admin\model\Scheme;
use app\BaseController;
use app\Request;
use app\admin\model\WorkJournal;
use fast\Tree;
use think\facade\Db;
use think\facade\View;
use app\admin\model\Admin;
use app\admin\model\JournalType;
use app\admin\model\JournaLevel;
use app\admin\common\Week;
use DateTime;
use DateInterval;
use DatePeriod;

/**
 *
 */
class Journal extends BaseController
{

    protected $childrenAdminIds = [];
    protected $group_id = "";
    protected $group_name = "";
    protected $groupList = "";
    protected $juese = null;

    public function initialize()
    {
        parent::initialize();

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groups = $this->auth->getGroups();
        foreach ($groups as $m => $n) {
            $this->juese = $n['name'];
        }
        $this->group_name = Department::find($this->auth->department_id);

        $journal_type = JournalType::select();
        $journal_level = JournaLevel::select();
        View::assign('journal_type', $journal_type);
        View::assign('username', $this->auth->nickname);
        View::assign('journal_level', $journal_level);

    }


    /**
     * [index description]显示资源
     * @param Request $request [description]
     * @return [type]           [description]
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');

            //获取当前页数
            $page = $request->param('page');

            $where = array();
            if ($request->has('admin_name') && !empty($request->get('admin_name'))) {
                $where[] = array("admin_name", "like", "%" . $request->get('admin_name') . "%");
            }
            if ($request->has('journal_type_id') && !empty($request->get('journal_type_id'))) {
                $where[] = array("journal_type_id", "=", $request->get('journal_type_id'));
            }
            if ($request->has('journal_level_id') && !empty($request->get('journal_level_id'))) {
                $where[] = array("journal_level_id", "=", $request->get('journal_level_id'));
            }
            if ($request->has('status') && !empty($request->get('status')) && $request->get('status') != -1) {
                $where[] = array("status", "=", $request->get('status'));
            }
            if ($request->has('status') && !empty($request->get('status')) && $request->get('status') == -1) {
                $where[] = array("status", "=", 0);
            }

            if ($this->juese != "综合运营部") {
                $where[] = array("admin_id", "in", $this->childrenAdminIds);
            }
//            $where[] = array("admin_id", "in", $this->auth->getChildrenAdminIds(true));
            $result = WorkJournal::with(['JournalType', 'JournaLevel'])->where($where)->order('id desc')->select()->toArray();

            foreach ($result as $key => $v) {
//                $v['task_status'] = checkTaskStatus('journals', $v['id']);
                if ($v['admin_id'] == $this->auth->id) {
                    $result[$key]['edit_auth'] = 1;
                } else {
                    if ($v['status'] == 0) {
                        unset($result[$key]);
                    } else {
                        $result[$key]['edit_auth'] = 2;
                    }
                }
            }
            $count = count($result);//总条数
            $start = ($page - 1) * $limit;//偏移量，当前页-1乘以每页显示条数
            $article = array_slice($result, $start, $limit);

            return json(['code' => 200, 'msg' => '', 'total' => $count, 'data' => $article]);
        }
        return View::fetch();
    }

    /**
     * [add description] 新增
     * @param Request $request [description]
     */
    public function add(Request $request)
    {
        $flow = \app\admin\model\Scheme::where('flowname', '日志')->select();
        if ($request->isAjax()) {
            $data = $request->only(['journal_type_id', 'admin_name', 'group_name', 'is_week', 'week_time', 'flow_id']);
            $data['journal_no'] = 'RZ_' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT) . date('Ymd', time());
            $data['admin_id'] = $this->auth->id;
            $data['group_id'] = $this->auth->department_id;
            $data['markdown_content'] = $request->param('content');
            $data['html_content'] = $request->param('test-editormd-html-code');
            $week_time = explode('至', $data['week_time']);
            $data['start_time'] = reset($week_time);
            $data['end_time'] = end($week_time);
            $switch = $request->param('switch');
            if ($switch == "on") { //选中状态
                $data['status'] = 1; //提交
                $result = WorkJournal::create($data);
                $scheme = Scheme::find($data['flow_id']);
                $serial_no = $this->getnumber($scheme['flowcode']);
                $this->flow = new FlowEngine($scheme['flowcode']);
                $config = [
                    'instancecode' => $serial_no,
                    'start_time' => date("Y-m-d H:i:s", time()),
                    'content' => $data['markdown_content'],
                    'from_id' => $result->id,
                    'from_table' => 'journals'
                ];
                $this->flow->start($config);
            } else {
                $result = WorkJournal::create($data);
            }
            $xingqi = $request->param('xingqi');
            $journ = [];
            foreach ($xingqi as $key => $value) {
                $journ[$key]['xingqi'] = $value;
                $journ[$key]['content'] = $request->param('one')[$key];
                $journ[$key]['jindu'] = $request->param('jindu')[$key];
                $journ[$key]['journ_id'] = $result->id;
            }
            $journ_week = new JournWeek();
            $journ_week->saveAll($journ);
            if ($result) {
                return json(['code' => 200, 'url' => '', 'msg' => '成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '未知错误']);
        }
        View::assign('group_name', $this->group_name['name']);
        View::assign('flow', $flow);
        return View::fetch();
    }

    /**
     * [select_type description]类别读取
     * @param Request $request [description]
     * @return [type]           [description]
     */
    public function select_type(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->param('id');
            $year = $request->param('year');

            $week = new Week();
            switch ($id) {
                case WorkJournal::WEEK:
                    $value = $week->get_week_all($year);
                    break;
                case WorkJournal::MONTH:
                    $value = $week->get_month();
                    break;
                case WorkJournal::QUARTER:
                    $season = ceil((date('n')) / 3);
                    $week_list = array();
                    $week_list[0]['detail'] = "第" . $season . '季度';
                    $week_list[0]['now'] = true;
                    $week_list[0]['fanwei'] = date('Y-m-d', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y'))) . '至' . date('Y-m-d', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
                    $value = $week_list;
                    break;
                case WorkJournal::YEAR:
                    $smonth = 1;
                    $emonth = 12;
                    $week_list = array();
                    $startTime = date('Y') . '-' . $smonth . '-1 00:00:00';
                    $em = date('Y') . '-' . $emonth . '-1 23:59:59';
                    $endTime = date('Y-m-t H:i:s', strtotime($em));
                    $week_list[0]['detail'] = date('Y') . '年';
                    $week_list[0]['now'] = true;
                    $week_list[0]['fanwei'] = date('Y-m-d', strtotime($startTime)) . '至' . date('Y-m-d', strtotime($endTime));
                    $value = $week_list;
                    break;
                default:
                    $value = "未知";
                    break;
            }

            return json_encode($value);
        }
    }

    /**
     * [edit description]编辑
     * @param Request $request [description]
     * @param  [type]  $id      [description]
     * @return [type]           [description]
     */
    public function edit(Request $request, $id)
    {
        $flow = \app\admin\model\Scheme::where('flowname', '日志')->select()->toArray();
        $model = WorkJournal::with('week')->find($id);
        $riqi = explode('至',$model['week_time'])[0] ?? date("Y-m-d");
        $model['year'] = explode('-',$riqi)['0'] ?? date("Y");
        if ($request->isAjax()) {
            $data = $request->only(['id', 'journal_type_id', 'admin_name', 'group_name', 'is_week', 'week_time', 'flow_id']);
            $data['journal_no'] = 'RZ_' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT) . date('Ymd', time());
            $data['admin_id'] = $this->auth->id;
            $data['group_id'] = $this->group_id;
            $data['markdown_content'] = $request->param('content');
            $data['html_content'] = $request->param('test-editormd-html-code');
            $week_time = explode('至', $data['week_time']);
            $data['start_time'] = reset($week_time);
            $data['end_time'] = end($week_time);
            $switch = $request->param('switch');
            if ($switch == "1") { //选中状态
                $data['status'] = 1; //提交
                $result = WorkJournal::update($data);
                $scheme = Scheme::find($data['flow_id']);
                $serial_no = $this->getnumber($scheme['flowcode']);
                $this->flow = new FlowEngine($scheme['flowcode']);
                $config = [
                    'instancecode' => $serial_no,
                    'start_time' => date("Y-m-d H:i:s", time()),
                    'content' => $data['markdown_content'],
                    'from_id' => $data['id'],
                    'from_table' => 'journals'
                ];
                $this->flow->start($config);
            } else {
                $result = WorkJournal::update($data);
            }
            $xingqi = $request->param('xingqi');
            $journ = [];
            foreach ($xingqi as $key => $value) {
                $journ[$key]['xingqi'] = $value;
                $journ[$key]['id'] = $request->param('week_id')[$key];
                $journ[$key]['content'] = $request->param('one')[$key];
                $journ[$key]['jindu'] = $request->param('jindu')[$key];
                $journ[$key]['journ_id'] = $data['id'];
            }
            $journ_week = new JournWeek();
            $journ_week->saveAll($journ);
            if ($result) {
                return json(['code' => 200, 'url' => '', 'msg' => '修改成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '未知错误']);
        }
        View::assign('flow', $flow);
        View::assign('model', $model);
        return View::fetch();
    }

    /**
     * [del description]删除项目 存在BUG
     * @param Request $request [description]
     * @param string $ids [description]
     * @return [type]           [description]
     */
    public function del(Request $request, $ids = "")
    {

        if ($request->isAjax() && $ids) {
            $ids = explode(',', $ids);
            // foreach ($ids as $key => $value) {
            // 	$journal = WorkJournal::find($value);
            // 	if ($journal->status != 0 || count($this->childrenAdminIds) >= 1) {
            // 		 return json(['code' => 400, 'url' => '', 'msg' => '当前状态，无法删除']);
            // 	}
            // }
            $count = WorkJournal::destroy(array_values($ids));
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
    }

    /**
     * [approval description]审核页面
     * @param Request $request [description]
     * @param  [type]  $id      [description]
     * @return [type]           [description]
     */
    public function approval(Request $request, $id)
    {
        $model = WorkJournal::find($id);
        if ($request->isAjax()) {
            $data = $request->param();
            $data['status'] = 2; //审批
            $data['approval_admin_id'] = $this->auth->id; //审批
            $find = WorkJournal::find($id);
            if ($find->status == 2) {
                return json(['code' => 400, 'url' => '', 'msg' => '已经审核请勿重复审核']);
            }
            $res = WorkJournal::update($data);
            if ($res) {
                return json(['code' => 200, 'url' => '', 'msg' => '审批成功']);
            }

        }
        View::assign('model', $model);
        return View::fetch();
    }

    /**
     * [grade description]评级
     * @param Request $request [description]
     * @param  [type]  $id      [description]
     * @return [type]           [description]
     */
    public function grade(Request $request, $id)
    {
        View::assign('id', $id);
        return View::fetch();
    }

    /**
     * [detail description]详情
     * @param string $id [description]
     * @return [type]     [description]
     */
    public function detail($id = '')
    {
        $model = WorkJournal::with(['JournalType', 'JournaLevel', 'Admin', 'week'])->find($id);
        $new_path = 'data:' . $model['path'];
        View::assign('model', $model);
        View::assign('new_path', $new_path);
        return View::fetch();
    }
}